﻿package 
{
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.external.ExternalInterface;
	import flash.system.*
	import flash.events.*;
    import flash.net.*;
	import flash.text.TextField;
	import flash.display.*;
	import com.adobe.serialization.json.*;

	/**
	 * ...
	 * @author egoing
	 */
	public class Main extends MovieClip 
	{
		//private var debug:TextField;
		private var tinyType:String;
		private var tinyURL:String;
		private var urlRegex:RegExp = /https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w\/_\.]*(\?\S+)?)?)?/igm;
		private var tinyRegex:RegExp = /http:\/\/bit.ly|http:\/\/tinyURL/ig;
			
		public function Main():void 
		{
			Security.allowDomain('*');
			var paramObj:Object = LoaderInfo(this.root.loaderInfo).parameters;
			tinyType = paramObj['tinyType'] == undefined ? 'bitly' : paramObj['tinyType'];
			tinyURL = paramObj['tinyURL'] == undefined ? 'http://api.bit.ly/shorten?version=2.0.1&login=egoing&apiKey=R_644d74992a0a12588389daff443ca860&longUrl=' : paramObj['tinyURL'];
			
			if (stage) init();
			else addEventListener(Event.ADDED_TO_STAGE, init);
			try {
				if(ExternalInterface.available){
					ExternalInterface.addCallback('convertTinyURL', convertTinyURL);
					ExternalInterface.addCallback('getTinyURL', getTinyURL);
				}
			} catch (e:Error) {
				//debug.text = e.message;
				trace(e);
			}
		}
		private function convertTinyURL(content:String):void {
			var result:Array = content.match(urlRegex);
			for (var i:Number = 0 ; i < result.length; i++) {
				var _url:String = result[i];
				if (_url.length > 20 && !tinyRegex.test(_url)) {
					getTinyURL(_url);
				}
			}
		}
		private function getTinyURL(url:String):void {
			var loader:URLLoaderDynamic = new URLLoaderDynamic();
			loader.temp = url;
			configureListeners(loader);
			var request:URLRequest = new URLRequest(tinyURL+url);
			try {
				loader.load(request);
			} catch (error:Error) {
				trace("Unable to load requested document.");
			}
		}
		private function init(e:Event = null):void 
		{
			removeEventListener(Event.ADDED_TO_STAGE, init);
			// entry point
		}
		
		 private function configureListeners(dispatcher:IEventDispatcher):void {
            dispatcher.addEventListener(Event.COMPLETE, completeHandler);
        }

        private function completeHandler(event:Event):void {
            var loader:URLLoaderDynamic = URLLoaderDynamic(event.target);
			var _tinyURL:String;
			var _result:Boolean = true;
			switch(tinyType) {
				case 'bitly':
					var r:Object = JSON.decode(loader.data);
					_tinyURL = r['results'][loader.temp]['shortUrl'];
					_result = r['results'][loader.temp]['statusCode'] == 'ERROR' ? false : true;
					break;
				case 'tinyURL':
					_tinyURL = loader.data;
					break;
			}
			trace(_tinyURL, loader.temp);
			if (ExternalInterface.available) {
				ExternalInterface.call('convertTinyURL', {original:loader.temp,tinyURL:_tinyURL, result:_result});
			}
        }
		
	}
}
	import flash.net.*;
	class URLLoaderDynamic extends URLLoader{
		public var temp:String;
	}